import { 
  REGISTER_USER_REQUEST, 
  REGISTER_USER_FAILURE, 
  REGISTER_USER_SUCCESS,
  GET_CODE_REQUEST, 
  GET_CODE_FAILURE, 
  GET_CODE_SUCCESS, 
  GET_CODE_OVER_TIME,
  CLEAR_ERROR
} from '../constants';
import CONFIG from '../../config';
import { login } from './LoginAc';
import { checkHttpStatus } from '../Helper';

export function registerUserRequest() {
  return { 
    type: REGISTER_USER_REQUEST
  }
}

export function registerUserFailure(error) {
  return {
    type: REGISTER_USER_FAILURE,
    payload: error
  }
}

export function registerUserSuccess() {
  return {
    type: REGISTER_USER_SUCCESS
  }
}

export function register(phone, password, verification_code) {
  return (dispatch) => {
    dispatch(registerUserRequest());
    return fetch(CONFIG.apiHost + '/api/register', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        phone: phone, 
        password: password,
        verification_code: verification_code
      })
    })
    .then(checkHttpStatus)
    .then(res => res.json())
    .then(res => {
      if(res.status){
        dispatch(registerUserSuccess());
        setTimeout(function(){
          dispatch(login(phone, password, '/i'));
        }, 3000);
      }
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        dispatch(registerUserFailure(v.msg));
        setTimeout(function(){dispatch(clearError())}, 4000);
      })
    })
  }
}

export function getCodeRequest() {
  return { 
    type: GET_CODE_REQUEST
  }
}

export function getCodeFailure(error) {
  return {
    type: GET_CODE_FAILURE,
    payload: error
  }
}

export function getCodeSuccess() {
  return {
    type: GET_CODE_SUCCESS
  }
}

export function getCodeOverTime() {
  return {
    type: GET_CODE_OVER_TIME
  }
}

export function sendCode(phone) {
  return (dispatch) => {
    dispatch(getCodeRequest());
    return fetch(CONFIG.apiHost + '/api/verification', {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        phone: phone
      })
    })
    .then(checkHttpStatus)
    .then(res => res.json())
    .then(res => {
      if (res.status) {
        dispatch(getCodeSuccess());
        setTimeout(function(){dispatch(getCodeOverTime())}, 90000);
        // 90秒后可以再次获取验证码
      }
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        dispatch(getCodeFailure(v.msg));
      })
    })
  }
}

export function clearError() {
  return {
    type: CLEAR_ERROR
  }
}